package com.atguigu.tingshu.search.strategy;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.search.repository.AlbumInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Optional;

@Component("1002")
public class ProcessTrackPurchases implements ProcessDiffTypePurchases{
    @Autowired
    private AlbumInfoRepository albumInfoRepository;
    @Qualifier("com.atguigu.tingshu.album.client.AlbumInfoFeignClient")
    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    /**
     * 处理声音类型购买量(声音没有购买量,修改声音对应的专辑购买量)(Es)
     * @param orderInfo 订单信息
     */
    @Override
    public void processTypePurchases(OrderInfo orderInfo) {
        Long trackId = orderInfo.getOrderDetailList().get(0).getItemId();
        //根据声音id获取声音信息
        Result<TrackInfo> trackInfoResult = albumInfoFeignClient.getTrackInfoById(trackId);
        TrackInfo trackInfo = trackInfoResult.getData();
        Assert.notNull(trackInfo, "远程调用获取声音信息失败");
        //获取声音对应的专辑id
        Long albumId = trackInfo.getAlbumId();
        //进行处理
        Optional<AlbumInfoIndex> optionalAlbumInfoIndex = albumInfoRepository.findById(albumId);
        optionalAlbumInfoIndex.ifPresent(albumInfoIndex -> {
            Integer buyStatNum = albumInfoIndex.getBuyStatNum();
            albumInfoIndex.setBuyStatNum(buyStatNum + orderInfo.getOrderDetailList().size());
            albumInfoRepository.save(albumInfoIndex);
        });
    }
}
